package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author mrchen
 * @date 2022/7/26 14:53
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1. 校验参数
        dto.checkParam();
        // 2. 执行查询
        // 2.1  分页条件
        Page<ApUserRealname> pageReq = new Page<>(dto.getPage(), dto.getSize());
        // 2.2  查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        // 2.3  执行查询
        if(dto.getStatus()!=null){
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = this.page(pageReq, queryWrapper);
        // 3. 封装分页结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;


    //@Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 300000)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        // 1. 校验参数
        if(dto.getId() ==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证id不能为空");
        }
        //   根据实名认证的id 查询实名认证信息
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (apUserRealname==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        //   判断实名认证的状态是否为待审核   (1   2   9)
        if(!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证不是待审核状态");
        }
        //   根据实名认证关联的userId 查询出apUser对象信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if(apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"未发现该实名认证关联的apuser信息");
        }
        // 2. 修改实名认证的状态
        apUserRealname.setStatus(status);
        apUserRealname.setReason(dto.getMsg());
        this.updateById(apUserRealname);
        // 3. 如果状态为 9
        if (AdminConstants.PASS_AUTH.equals(status)) {
            // 3.1  开通自媒体账户
            WmUser wmUser = createWmUser(apUser);
            // 3.2   创建作者信息
            createAuthor(wmUser,apUser);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    ArticleFeign articleFeign;

    /**
     * 远程创建作者信息
     * @param wmUser
     * @param apUser
     */
    private void createAuthor(WmUser wmUser, ApUser apUser) {
        // 1. 先根据apUserId远程查询作者信息
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        // 2. 判断作者信息是否存在
        ApAuthor apAuthor = result.getData();

        if(apAuthor!=null){
            // 3. 如果存在，提示 作者已存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已经存在，创建失败");
        }
        // 4. 如果不存在， 创建作者信息
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        // 5. 远程保存作者信息
        articleFeign.save(apAuthor);
    }

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 远程开通自媒体账户
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        // 1. 根据用户名 远程查询自媒体账户
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        // 2. 如果有该用户 抛出异常 自媒体用户已存在
        if(wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"自媒体用户已存在，开通失败");
        }
        // 3. 如果没有该用户  创建 新的自媒体用户
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        // 4. 远程保存自媒体用户
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (!saveResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return saveResult.getData();
    }
}